package com.itheima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmMaterial;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public WmUser getByAppUserId(Integer appUserId) {
        WmUser wmuser = query().eq("ap_user_id", appUserId).one();
        return wmuser;
    }

    @Override
    public Map<String, Object> login(Map<String, String> map) {
        //1.获取参数
        String name = map.get("name");
        String password = map.get("password");
        //2.参数校验
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("账号或密码为空");
        }
        //3.通过登录用户名查询
        WmUser wmUser = query().eq("name", name).one();
        if (null == wmUser) {
            //3.1不存在，则报错
            throw new LeadNewsException("账号或密码错误");
        }
        //4.密码校验
        //4.1对密码加盐加密
        password+=wmUser.getSalt();
        String digest = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!wmUser.getPassword().equals(digest)) {
            //4.2把加盐加密后的密码和数据库校验
            //4.3不一致则报错
         throw new LeadNewsException("账号或密码错误");
        }
        //5.校验通过则生成tocken
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        //6.封装返回
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("user",wmUser);

        return hashMap;
    }


}
